﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing;

namespace MyCleverMissionEditor
{
    class LogTabPage : TabPage
    {
        private RichTextBox loggingTextBox;
        private LogWatcher watcher;

        public string LoggingFile
        {
            set
            {
                this.CreateWatcher(value);
            }
        }

        //Constructor for the LogTabPage
        public LogTabPage()
        {
            this.loggingTextBox = new RichTextBox();
            this.loggingTextBox.Dock = DockStyle.Fill;
            this.loggingTextBox.BackColor = Color.White;
            this.loggingTextBox.ReadOnly = true;
            this.Controls.Add(loggingTextBox);
            
            this.Text = "Logging";
        }

        private void CreateWatcher(string logFileName)
        {
            this.watcher = new LogWatcher(logFileName);
            this.watcher.Path = Path.GetDirectoryName(logFileName);

            //Raise events when the LastWrite or Size attribute is changed
            this.watcher.NotifyFilter = (NotifyFilters.LastWrite | NotifyFilters.Size);

            //Filter out events for only this file
            this.watcher.Filter = Path.GetFileName(logFileName);

            //Subscribe to the event
            this.watcher.TextChanged += new LogWatcher.LogWatcherEventHandler(LogFileChanged);

            //Enable the event
            this.watcher.EnableRaisingEvents = true;
        }

        void LogFileChanged(object sender, LogWatcherEventArgs e)
        {
            //Invoke the AppendText method if required
            if (this.loggingTextBox.InvokeRequired)
            {
                this.Invoke(new Action(delegate() { AppendText(e.Contents); }));
            }
            else
            {
                this.AppendText(e.Contents);
            }
        }

        public void AppendText(string Text)
        {
            this.loggingTextBox.Text += Text;

            //scroll to the bottom of the TextBox
            this.loggingTextBox.SelectionStart = this.loggingTextBox.Text.Length;
            this.loggingTextBox.SelectionLength = 0;
            this.loggingTextBox.ScrollToCaret();
        }
    }
}

